package com.cscj.android.repository.db.dao

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.cscj.android.repository.db.entity.FavoritesEntity
import kotlinx.coroutines.flow.Flow

@Dao
interface FavoritesDao {

    @Query("delete from favorite where id in (:ids)")
    suspend fun deleteByIds(ids: IntArray)

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    suspend fun addFavorites(favoritesEntity: FavoritesEntity)

    @Query("select * from favorite order by id")
    fun allFavorites(): Flow<List<FavoritesEntity>>

    @Query("select * from favorite where id != ${FavoritesEntity.RootId} order by addDate desc")
    fun favorites(): Flow<List<FavoritesEntity>>

    @Query("select * from favorite where id != ${FavoritesEntity.RootId} and (title like :keyword or url like :keyword) order by addDate desc")
    fun favorites(keyword: String): Flow<List<FavoritesEntity>>

    @Query("select count(1) from favorite where url = :url")
    fun favoriteCount(url: String): Flow<Int>

    @Query("delete from favorite where url = :url")
    suspend fun deleteByUrl(url: String)

    @Query("update favorite set icon = :favicon where url = :url")
    suspend fun updateFavicon(url: String, favicon: String?)

    @Query("delete from favorite")
    suspend fun deleteAll()

}